package com.api.gbhg.huangwm.budget;

import com.alibaba.fastjson.JSONObject;
import com.api.gbhg.huangwm.dao.RevenueBudgetDao;
import com.api.gbhg.huangwm.dao.YuSuanTiaoZhengDao;
import com.customization.commons.LogTool;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.*;

/**
 * @Author Huangwm
 * @Date 2023-07-04
 * @Version 1.0
 * @Description TODO 预算核批渠道调整 针对02结构的表 明细5，明细6为结构
 **/
public class AmountWayAdjust implements Action {

    private LogTool logTool = new LogTool("/log/gbhg/huangwm/action/AmountWayAdjust",false);

    private final String SUCCESS = "1";
    private final String FAILURE_AND_CONTINUE = "0";

    private YuSuanTiaoZhengDao dao = new YuSuanTiaoZhengDao();

    @Override
    public String execute(RequestInfo requestInfo) {
        RequestManager requestManager = requestInfo.getRequestManager();
        int requestid = requestManager.getRequestid();
        int billid = requestManager.getBillid();
        String tablename = requestManager.getBillTableName();
        int formid = requestInfo.getRequestManager().getFormid();
        logTool.writeLog("预算核批渠道调整 requestid="+requestid);

        Map<String,String> data = new HashMap<>();
        data.put("requestid",requestid+"");
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        for(Property property : properties){
            data.put(property.getName().toLowerCase(),property.getValue());
        }
        String dzxm = data.get("dzxm");
        String szdlhsdw = data.get("szdlhsdw");//所属独立核算单位

        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);

        rs.execute("select ysnd,sbdw from uf_jingfei_version where lcjlsqjlid="+dzxm);
        rs.next();
        String ysnd = rs.getString("ysnd");
        String sbdw = rs.getString("sbdw");

        try{

            //更新经济分类
            RecordSet jjfl = new RecordSet();
            String jjfltable = dao.getJjfl_DtTablesNoZSXM(formid);
            jjfl.execute("select * from "+jjfltable+" where mainid="+billid);
            while (jjfl.next()){
                Double dzje = jjfl.getDouble("dzje");//调整金额
                String bmyszcjjfl = jjfl.getString("bmyszcjjfl");
                String sql = "update uf_jingfei set ze=ze+"+dzje+",syed=syed+"+dzje+" where lcjlid="+dzxm+" and bmzcjjfl="+bmyszcjjfl;
                logTool.writeLog("合并经济分类:"+sql);
                boolean f1 = rst.execute(sql);
                if(!f1){
                    rst.rollback();
                    requestManager.setMessagecontent("合并经济分类数据失败 ");
                    requestManager.setMessageid(requestid+"");
                    return FAILURE_AND_CONTINUE;
                }
            }

            List<String> HPQD = dao.getHpqd_DtTablesNoZSXM(formid);//获取核批渠道明细表名称

            //获取上年结转和当年预算的明细数据
            RecordSet snjz = new RecordSet();
            snjz.execute("select * from "+HPQD.get(1) +" where isnull(did,'')='' and mainid="+billid);
            while (snjz.next()){
                String srlx = snjz.getString("srlx");//0-财政 1-非财政
                String zyczbksr = snjz.getString("zyczbksr");//财政拨款来源
                String zcqd = snjz.getString("zcqd");//非财政拨款收入类型
                String dfczbkxmsnjz = snjz.getString("dfczbkxmsnjz");//地方财政拨款项目
                Double hpje = snjz.getDouble("hpje");//核批金额

                boolean f1 = false;
                boolean f2 = false;//uf_ysbzyxeshpsj_dt1

                if(srlx.equals("0")){
                    rs.execute("select * from uf_jingfeilaiyuan where lcid="+dzxm+" and srlx=0 and yslylx='上年结转核批' and zyczbksr='"+zyczbksr+"'");
                    if(rs.next()){
                        String lyid = rs.getString("id");
                        String sql = "update uf_jingfeilaiyuan set je=je+"+hpje+",syed=syed+"+hpje+" where id="+lyid;
                        logTool.writeLog("存在来源,合并:"+sql);
                        f1 = rst.execute(sql);
                    }else {
                        //插入
                        Map map = new HashMap();
                        map.put("sbdw", sbdw);
                        map.put("nd", ysnd);
                        //来源类型
                        map.put("zcqd", zcqd);
                        //功能科目
                        map.put("gnkm", "");
                        //金额
                        map.put("je", hpje);
                        //剩余额度
                        map.put("syed", hpje);
                        //冻结金额
                        map.put("djje", 0);
                        //预算来源类型
                        map.put("yslylx", "上年结转核批");
                        //收入类型
                        map.put("srlx", srlx);
                        //地方财政拨款项目上年结转
                        map.put("dfczbkxm", dfczbkxmsnjz);
                        //中央财政拨款收入
                        map.put("zyczbksr", zyczbksr);
                        map.put("lcid", dzxm);

                        f1 = storageDateToJingfeiLy(map);
                    }
                    //合并更新uf_ysbzyxeshpsj_dt1核批记录
                    String sql2 = "insert into uf_ysbzyxeshpsj_dt1(mainid,mxid,srlx,zyczbksr,zcqd,dfczbkxmsnjz,hpje)values(?,?,?,?,?,?,?)";
                    rs.execute(" select * from uf_ysbzyxeshpsj_dt1 where mainid="+dzxm+" and srlx=0 and zyczbksr='"+zyczbksr+"' ");
                    if(rs.next()){
                        String hpjlid = rs.getString("id");
                        String sql = "update uf_ysbzyxeshpsj_dt1 set hpje=hpje+"+hpje+" where id="+hpjlid;
                        f2 = rst.execute(sql);
                        logTool.writeLog("合并核批记录上年结转:"+sql);
                    }else{
                        Object[] objects = {
                                dzxm,0,srlx,zyczbksr,zcqd,dfczbkxmsnjz,hpje
                        };
                        f2 = rst.executeUpdate(sql2,objects);
                    }

                }else{
                    rs.execute("select * from uf_jingfeilaiyuan where lcid="+dzxm+" and srlx=1 and yslylx='上年结转核批' and zcqd="+zcqd+" and ISNULL(dfczbkxm,'')='"+dfczbkxmsnjz+"' ");
                    if(rs.next()){
                        String lyid = rs.getString("id");
                        String sql = "update uf_jingfeilaiyuan set je=je+"+hpje+",syed=syed+"+hpje+" where id="+lyid;
                        logTool.writeLog("存在来源,合并:"+sql);
                        f1 = rst.execute(sql);
                    }else {
                        //插入
                        Map map = new HashMap();
                        map.put("sbdw", sbdw);
                        map.put("nd", ysnd);
                        //来源类型
                        map.put("zcqd", zcqd);
                        //功能科目
                        map.put("gnkm", "");
                        //金额
                        map.put("je", hpje);
                        //剩余额度
                        map.put("syed", hpje);
                        //冻结金额
                        map.put("djje", 0);
                        //预算来源类型
                        map.put("yslylx", "上年结转核批");
                        //收入类型
                        map.put("srlx", srlx);
                        //地方财政拨款项目上年结转
                        map.put("dfczbkxm", dfczbkxmsnjz);
                        //中央财政拨款收入
                        map.put("zyczbksr", zyczbksr);
                        map.put("lcid", dzxm);

                        f1 = storageDateToJingfeiLy(map);
                    }

                    //合并更新uf_ysbzyxeshpsj_dt2核批记录
                    String sql2 = "insert into uf_ysbzyxeshpsj_dt1(mainid,mxid,srlx,zyczbksr,zcqd,dfczbkxmsnjz,hpje)values(?,?,?,?,?,?,?)";
                     rs.execute(" select * from uf_ysbzyxeshpsj_dt1 where mainid="+dzxm+" and srlx=1 and and zcqd="+zcqd+" and ISNULL(dfczbkxm,'')='"+dfczbkxmsnjz+"' ");
                    if(rs.next()){
                        String hpjlid = rs.getString("id");
                        String sql = "update uf_ysbzyxeshpsj_dt1 set hpje=hpje+"+hpje+" where id="+hpjlid;
                        f2 = rst.execute(sql);
                        logTool.writeLog("合并核批记录上年结转:"+sql);
                    }else{
                        Object[] objects = {
                                dzxm,0,srlx,zyczbksr,zcqd,dfczbkxmsnjz,hpje
                        };
                        f2 = rst.executeUpdate(sql2,objects);
                    }

                }
                if(!f1){
                    rst.rollback();
                    requestManager.setMessagecontent("合并上年结转经费来源表失败 ");
                    requestManager.setMessageid(requestid+"");
                    return FAILURE_AND_CONTINUE;
                }
                if(!f2){
                    rst.rollback();
                    requestManager.setMessagecontent("合并上年结转核批数据表失败 ");
                    requestManager.setMessageid(requestid+"");
                    return FAILURE_AND_CONTINUE;
                }

            }

            RecordSet dnys = new RecordSet();
            dnys.execute("select * from "+HPQD.get(0) +" where isnull(did,'')='' and mainid="+billid);
            while (dnys.next()){
                String srlx = dnys.getString("srlx");//0-财政 1-非财政
                String zyczbksr = dnys.getString("zyczbksr");//财政拨款来源
                String zcqd = dnys.getString("zcqd");//非财政拨款收入类型
                String dfczbkxmdnys = dnys.getString("dfczbkxmdnys");//地方财政拨款项目
                Double hpje = dnys.getDouble("hpje");//核批金额

                boolean f1 = false;
                boolean f2 = false;//uf_ysbzyxeshpsj_dt2

                if(srlx.equals("0")){
                    rs.execute("select * from uf_jingfeilaiyuan where lcid="+dzxm+" and srlx=0 and yslylx='当年预算核批' and zyczbksr='"+zyczbksr+"'");
                    if(rs.next()){
                        String lyid = rs.getString("id");
                        String sql = "update uf_jingfeilaiyuan set je=je+"+hpje+",syed=syed+"+hpje+" where id="+lyid;
                        logTool.writeLog("存在来源,合并:"+sql);
                        f1 = rst.execute(sql);
                    }else {
                        //插入
                        Map map = new HashMap();
                        map.put("sbdw", sbdw);
                        map.put("nd", ysnd);
                        //来源类型
                        map.put("zcqd", zcqd);
                        //功能科目
                        map.put("gnkm", "");
                        //金额
                        map.put("je", hpje);
                        //剩余额度
                        map.put("syed", hpje);
                        //冻结金额
                        map.put("djje", 0);
                        //预算来源类型
                        map.put("yslylx", "当年预算核批");
                        //收入类型
                        map.put("srlx", srlx);
                        //地方财政拨款项目上年结转
                        map.put("dfczbkxm", dfczbkxmdnys);
                        //中央财政拨款收入
                        map.put("zyczbksr", zyczbksr);
                        map.put("lcid", dzxm);

                        f1 = storageDateToJingfeiLy(map);
                    }

                    String sql3 = "insert into uf_ysbzyxeshpsj_dt2(mainid,mxid,srlx,zyczbksr,zcqd,dfczbkxmdnys,hpje)values(?,?,?,?,?,?,?)";
                    rs.execute(" select * from uf_ysbzyxeshpsj_dt2 where mainid="+dzxm+" and srlx=0 and zyczbksr='"+zyczbksr+"' ");
                    if(rs.next()){
                        String hpjlid = rs.getString("id");
                        String sql = "update uf_ysbzyxeshpsj_dt2 set hpje=hpje+"+hpje+" where id="+hpjlid;
                        f2 = rst.execute(sql);
                        logTool.writeLog("合并核批记录当年预算:"+sql);
                    }else{
                        Object[] objects = {
                                dzxm,0,srlx,zyczbksr,zcqd,dfczbkxmdnys,hpje
                        };
                        f2 = rst.executeUpdate(sql3,objects);
                    }
                }else{
                    rs.execute("select * from uf_jingfeilaiyuan where lcid="+dzxm+" and srlx=1 and yslylx='当年预算核批' and zcqd="+zcqd+" and ISNULL(dfczbkxm,'')='"+dfczbkxmdnys+"' ");
                    if(rs.next()){
                        String lyid = rs.getString("id");
                        String sql = "update uf_jingfeilaiyuan set je=je+"+hpje+",syed=syed+"+hpje+" where id="+lyid;
                        logTool.writeLog("存在来源,合并:"+sql);
                        f1 = rst.execute(sql);
                    }else {
                        //插入
                        Map map = new HashMap();
                        map.put("sbdw", sbdw);
                        map.put("nd", ysnd);
                        //来源类型
                        map.put("zcqd", zcqd);
                        //功能科目
                        map.put("gnkm", "");
                        //金额
                        map.put("je", hpje);
                        //剩余额度
                        map.put("syed", hpje);
                        //冻结金额
                        map.put("djje", 0);
                        //预算来源类型
                        map.put("yslylx", "当年预算核批");
                        //收入类型
                        map.put("srlx", srlx);
                        //地方财政拨款项目上年结转
                        map.put("dfczbkxm", dfczbkxmdnys);
                        //中央财政拨款收入
                        map.put("zyczbksr", zyczbksr);
                        map.put("lcid", dzxm);

                        f1 = storageDateToJingfeiLy(map);
                    }
                    //合并更新uf_ysbzyxeshpsj_dt2核批记录
                    String sql3 = "insert into uf_ysbzyxeshpsj_dt2(mainid,mxid,srlx,zyczbksr,zcqd,dfczbkxmdnys,hpje)values(?,?,?,?,?,?,?)";
                    rs.execute(" select * from uf_ysbzyxeshpsj_dt2 where mainid="+dzxm+" and srlx=1 and and zcqd="+zcqd+" and ISNULL(dfczbkxm,'')='"+dfczbkxmdnys+"' ");
                    if(rs.next()){
                        String hpjlid = rs.getString("id");
                        String sql = "update uf_ysbzyxeshpsj_dt1 set hpje=hpje+"+hpje+" where id="+hpjlid;
                        f2 = rst.execute(sql);
                        logTool.writeLog("合并核批记录上年结转:"+sql);
                    }else{
                        Object[] objects = {
                                dzxm,0,srlx,zyczbksr,zcqd,dfczbkxmdnys,hpje
                        };
                        f2 = rst.executeUpdate(sql3,objects);
                    }
                }
                if(!f1){
                    rst.rollback();
                    requestManager.setMessagecontent("合并当年预算经费来源数据表失败 ");
                    requestManager.setMessageid(requestid+"");
                    return FAILURE_AND_CONTINUE;
                }
                if(!f2){
                    rst.rollback();
                    requestManager.setMessagecontent("合并当年预算核批渠道数据表失败 ");
                    requestManager.setMessageid(requestid+"");
                    return FAILURE_AND_CONTINUE;
                }
            }

            //重新扣减收入预算
            List<Map<String,String>> snjzDatas = getSNDatas_NoDid(HPQD.get(1),billid+"");
            List<Map<String,String>> dnysDatas = getDNDatas_NoDid(HPQD.get(0),billid+"");
            Map<String, Object> result = new RevenueBudgetDao().RevenueBudgetDeduction(snjzDatas,dnysDatas,Integer.parseInt(szdlhsdw),ysnd);
            logTool.writeLog("预算调整扣减收入预算结果："+ JSONObject.toJSONString(result));
            if(!result.get("code").equals("1")){
                String f1 = result.get("f1").toString();
                String f2 = result.get("f2").toString();
                String f3 = result.get("f3").toString();
                String f4 = result.get("f4").toString();
                String f5 = result.get("f5").toString();
                String f6 = result.get("f6").toString();
                String f7 = result.get("f7").toString();
                String f8 = result.get("f8").toString();
                String msg = "<br />"+f1+f2+f3+f4+f5+f6+f7+f8;
                rst.rollback();
                requestInfo.getRequestManager().setMessageid(requestInfo.getRequestid());
                requestInfo.getRequestManager().setMessagecontent("根据预算调整金额扣减收入预算失败 "+msg);
                return  FAILURE_AND_CONTINUE;
            }
        }catch (Exception e){
            rst.rollback();
            e.printStackTrace();
            requestManager.setMessagecontent("更新渠道异常  "+e.getMessage());
            requestManager.setMessageid(requestid+"");
            return FAILURE_AND_CONTINUE;
        }
        rst.commit();
        logTool.writeLog("action执行成功");
        return SUCCESS;
    }

    public boolean storageDateToJingfeiLy(Map map) {
        boolean flag = false;
        Set set = map.keySet();
        List<String> listField = new ArrayList<String>(set);
        // 上年结转
        Collection<String> valueCollection = map.values();
        List<String> valueList = new ArrayList<>(valueCollection);
        // 存储数据到经费来源表
        RecordSetTrans rst = new RecordSetTrans();
        String uf_jingfeilaiyuansql = dao.getInsertSql(listField, "uf_jingfeilaiyuan");
        try {
            logTool.writeLog("插入经费来源sq:" + uf_jingfeilaiyuansql + valueCollection);
            flag = rst.executeUpdate(uf_jingfeilaiyuansql, valueList.toArray());
        } catch (Exception e) {
            e.printStackTrace();
            logTool.writeLog("error:" + e.toString());
            return  false;
        }
        return flag;
    }

    /**
     * 根据上年结转核批明细表和流程mainid获取明细数据 过滤did
     * @param snDetailTable
     * @param mainid
     * @return
     */
    public List<Map<String,String>> getSNDatas_NoDid(String snDetailTable, String mainid){
        List<Map<String,String>> snjzDatas = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = "select id,srlx,zyczbksr,zcqd,dfczbkxmsnjz,hpje,ysjs from "+snDetailTable+" where isnull(did,'')='' and mainid="+mainid;
        rs.execute(sql);
        while (rs.next()){
            Map<String,String> data = new HashMap<>();
            data.put("id", rs.getString("id"));//明细表id
            data.put("srlx", rs.getString("srlx"));//收入预算 0和1 代表财政拨款和非财政拨款
            data.put("zyczbksr", Util.null2String(rs.getString("zyczbksr")));//中央财政拨款收入时的财政拨款预算来源
            data.put("zcqd", Util.null2String(rs.getString("zcqd")));//非财政拨款时的非财政拨款预算来源
            data.put("dfczbkxmsnjz", Util.null2String(rs.getString("dfczbkxmsnjz")));//非财政拨款时的非财政拨款项目
            data.put("hpje", rs.getString("hpje"));//拿核批金额
            snjzDatas.add(data);
        }
        return snjzDatas;
    }

    /**
     * 根据当年预算核批明细表和流程mainid获取明细数据 过滤did
     * @param dnDetailTable
     * @param mainid
     * @return
     */
    public List<Map<String,String>> getDNDatas_NoDid(String dnDetailTable,String mainid) {
        List<Map<String,String>> dnysDatas = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = "select id,srlx,zyczbksr,zcqd,dfczbkxmdnys,hpje,ysjs from "+dnDetailTable+" where isnull(did,'')='' and mainid="+mainid;
        rs.execute(sql);
        while (rs.next()){
            Map<String, String> data = new HashMap<>();
            data.put("id", rs.getString("id"));//明细表id
            data.put("srlx", rs.getString("srlx"));//收入预算 0和1 代表财政拨款和非财政拨款
            data.put("zyczbksr", rs.getString("zyczbksr"));//中央财政拨款收入时的财政拨款预算来源
            data.put("zcqd", rs.getString("zcqd"));//非财政拨款时的非财政拨款预算来源
            data.put("dfczbkxmdnys", rs.getString("dfczbkxmdnys"));//非财政拨款时的非财政拨款项目
            data.put("hpje", rs.getString("hpje"));//拿核批金额
            dnysDatas.add(data);
        }
        return dnysDatas;
    }
}
